(function($) {
	var methods = {
			"init": function(options){
				$.extend( $.mtgpi.global, options );
				return this.each(function(){
					$.mtgpi.create();
				});
			}
		};

	$.mtgpi = {};
	
	$.mtgpi.global = {
		//global variables
		"containingDiv": "mtgBody",
		"mtgID": null,
		"mtgType": null,
		"mtgStarter": null,
		"attendantMode": null,
		"aliases": [],
		"users": [],
		"admins": [],
		"signedIn": [],
		"keepFocus": true
	};
	
	$.fn.marcMeeting = function( method ) {	    
		// Method calling logic
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.dialogPrompt' );
		}
	};
	
	//PRIMARY PROGRAM LOGIC FUNCTION
	$.mtgpi.create = function()
	{
		//first, fire off a call to gather info on any active meetings
		$.ajax({ 
	  	  	url:"/marc/MeetingSigninService",
	  	  	data:{"RequestType":"CheckForOpenMeetings"},
			type:'POST',
			dataType:"json",
			success: function(html)
			{
				//if data is returned, store it for use below 
				var _meetingIDs = html['MeetingIDs'];
				var _meetingTypes = html['MeetingTypes'];
				var _meetingStarters = html['MeetingStarters'];
				var _meetingAttendant = html['MeetingAttendant'];
				
				//if the number of active meetings is 1, save it's values and return
				if(_meetingIDs.length  == 1)
				{
					$.mtgpi.global.mtgID = _meetingIDs[0];
					$.mtgpi.global.mtgType = _meetingTypes[0];
					$.mtgpi.global.mtgStarter = _meetingStarters[0];
					$.mtgpi.global.attendantMode = _meetingAttendant[0];
					
					//Load sign in page
					if(_meetingAttendant[0] == 1)
					{
						$.mtgpi.loadAttendedPlugin();
					}
					else
					{
						$.mtgpi.loadAttendedPlugin(); //TODO change to defaultPlugin?
					}
				}
				
				//if more than one meeting is returned, ask the user which they want to join
				else if(_meetingIDs.length > 1)
				{
					//create a dropdown to pick which meeting to join
					var _options = $('<select>').attr('id','activeMeetings');
					
					//for each meeting type, create an option in the dropdown
					for(var i=0; i<_meetingTypes.length; i++)
					{
						var thisType = _meetingTypes[i];
						_options.append(
								$('<option>')
									.attr({
										'id':i,
										'value':thisType
									})
									.text(thisType + "	(#" + _meetingIDs[i] + ")")
						);
					};
					
					//create a div for the multiple meeting dialog
					$.mtgpi.global.containingDiv.append(
						$('<div>')
							.attr('id','multipleMtgDialog')
							.append($('<center>')
							.append($('<img>')
									.attr('src','img/alert.png')
									.css('height','100px'))
							.append($('<br>')).append($('<br>'))
							.append("There are currently " + _meetingIDs.length + " meetings active. <br>Which would you like to join?")
							.append($('<form>').attr('id','pickAMeetingForm').append(_options).append($('<input>').attr({'type':'submit', 'value':'Join!'}))))
					);
					
					//when the user picks a meeting...
					$('#pickAMeetingForm').submit(function(e)
					{
						//stop the page from reloading
						e.preventDefault();
						
						//apply the chosen values to the global variables
						$.mtgpi.global.mtgID = _meetingIDs[$('#activeMeetings option:selected').attr('id')];
						$.mtgpi.global.mtgType = _meetingTypes[$('#activeMeetings option:selected').val()];
						$.mtgpi.global.mtgStarter = _meetingStarters[$('#activeMeetings option:selected').attr('id')];
						$.mtgpi.global.attendantMode = _meetingAttendant[$('#activeMeetings option:selected').attr('id')];
						
						//get rid of the dialog
						$('#multipleMtgDialog').dialog('close');
						$('#multipleMtgDialog').remove();
						
						$.mtgpi.loadDefaultPlugin();
					});
					
					//actually display the dialog, and tell it where to go
					$('#multipleMtgDialog').dialog();
					$('#multipleMtgDialog').dialog( "option", "width", '75%' );
					$('#multipleMtgDialog').dialog( "option", "position", 'center' );
				}
				//otherwise, there aren't any active meetings; return to sender
				else
				{
					alert('There are no active meetings. Please return to the admin page to start one.');
					window.location = "index.jsp";
				}
				
				//last, get the list of all available aliases
				$.mtgpi.gatherAliasInfo();
			},
			error: function(html)
			{
				alert("An error occured while gathering Active Meeting data." +
						"\nPlease refresh your browser and try again." +
						"\n\nIf problem persists please contact BigHelp Ministries.");
			}
		}); //Closes AJAX
	};
	
	$.mtgpi.gatherAliasInfo = function()
	{
		var _mtgID = $.mtgpi.global.mtgID;
		//ajax call to get list of active ID - user pairs
		$.ajax({ 
	  	  	url:"/marc/MeetingSigninService",
	  	  	data:
	  	  	{	"RequestType":"getActiveList", 
	  	  		"MeetingID": _mtgID
	  	  	},
			type:'POST',
			dataType:"json",
			success: function(html)
			{
				var _aliases = html['ActiveAliases'];
				var _users = html['ActiveUsers'];
				var _admins = html['ActiveAdmins'];
				var _signedIn = html['inUsers'];
				
				var _fullList = _aliases.concat(_users);
				
				$.mtgpi.global.aliases = _fullList;
				$.mtgpi.global.users = _users;
				$.mtgpi.global.admins = _admins;
				$.mtgpi.global.signedIn = _signedIn;
			},
	  	  	error: function(html)
			{
				alert("An error occured while gathering Active User data." +
						"\nPlease refresh your browser and try again." +
						"\n\nIf problem persists please contact BigHelp Ministries.");
			}
		}); //Closes AJAX
	};
	
	$.mtgpi.loadAttendedPlugin = function()
	{
		var _appBody = $('#'+$.mtgpi.global.containingDiv);
		
		_appBody.append(
			$('<div>')
				.attr({
					'id':'controlColumn'
				})
				.css({
				    'border-right':'1px solid #333333',
				    'top':'10px',
					'left':'5px',
					'height':'98%',
					'width':'24%',
					'position':'absolute'
				})
				.append(
					$('<center>')
						.append(
							$('<img>')
								.attr({
									'src':'img/marc_logo.jpg',
									'height':'100'
								})
						).append($('<br/>'))
						.append(
							$('<a>')
								.attr({
									'href':'#'
								})
								.append(
									$('<img>')
										.attr({
											'src':'img/search-by-name.jpg',
											'id':'peopleSearch'
										})
										.css({
											'margin-top':'30px',
											'margin-right':'50%',
											'width':'85%',
											'position':'relative'
										})
								)
						)
					)
			)
			.append(
				$('<div>')
					.attr({
						'id':'memberColumn'
					})
					.css({
						'border':'2px solid red',
					    'top':'10px',
						'left':'25%',
						'height':'98%',
						'width':'50%',
						'position':'absolute'
					})
					.append(
						$('<center>')
							.append(
								$('<form>')
									.attr('id','aliasEntryForm')
									.append($('<input>')
										.attr({
											'id':'aliasEntryBox',
											'type':'text'
										})
									)
									.css({
											'top':'15px',
											'position':'relative',
											'size':'50'
										}).append($('<br/>'))
							).append($('<br/>'))
							.append(
								$('<img>')
									.attr({
										'id':'logoImg',
										'src':'img/logo.png'
									})
									.css({
										'margin-top':'5%',
										'position':'relative'
									})
							)
					)
			)
			.append(
				$('<div>')
					.attr({
						'id':'meetingColumn'
					})
					.css({
						'border-left':'1px solid #333333',
					    'top':'10px',
						'right':'5px',
						'height':'98%',
						'width':'24%',
						'position':'absolute'
					})
			);
			$('#aliasEntryBox').val('').focus();
			$('#aliasEntryBox').blur(function()
			{
				setTimeout(function()
				{
					if($.mtgpi.global.keepFocus == true)
					{
						$('#aliasEntryBox').focus();
					}
				}, 1000);
			});
			
			$('#peopleSearch').click(function()
			{
				//keep js from locking back onto the aliasEntryBox
				$.mtgpi.global.keepFocus = false;
				
				//scrollable div with namepicker and people icons
				$('#globalSettings').append(
						$('<div>')
							.attr({'id':'aliasPicker', 'title':'Choose your ID:', 'height':'50%', 'width':'75%'})
					);

				//create a list of users for the name picker
				var _options = [];
				var _activeUsers = $.mtgpi.global.users;
				$.each(_activeUsers, function(index, _currUser) 
				{ 
					var _user = $.mtgpi.parseAlias(_currUser['UserID']);
					if(_user['IsAlreadyIn'] == false)
						_options.push($('<option>').attr('value',_currUser['UserID']).text(_currUser['LName'] + ', ' + _currUser['Pref_Name']));
				});
				
				$('#aliasPicker')
				.append($('<h4>')
					.append($('<form>').attr({'id':'pickAliasForm'})
						.append("Search by Last Name: ")
						.append(
							$('<select>')
								.attr('id','lnamePicker')
								.append(_options)
						)
					)
				);

				$('#aliasPicker').dialog({
						buttons: 
						{
							'Sign In': function()
							{
								var _selectedUser = $('#lnamePicker')[0].value;
								$('#aliasPicker').dialog("close").remove();
								$.mtgpi.SignInUser(_selectedUser, $('#globalSettings'));
								$('#aliasEntryBox').val('').focus();
								$.mtgpi.global.keepFocus = true;
							},
							'Cancel': function()
							{
								$('#aliasPicker').dialog("close").remove();
								$('#aliasEntryBox').val('').focus();
								$.mtgpi.global.keepFocus = true;
							}
						}
					});
					$('#aliasNotFoundDialog').dialog( "option", "width", "100%" );
					$('#aliasNotFoundDialog').dialog( "option", "position", 'center' );
				
				$('#aliasEntryBox').val('').focus();
			});
			
			$('#aliasEntryForm').submit(function(e)
			{
				//Stop the form from refreshing the page
				e.preventDefault();
				
				//Get the list of active users from global, and the entered alias from the textbox
				var _enteredAlias = $('#aliasEntryBox').val();
				
				//send the data down to the SignInUser function for parsing
				$.mtgpi.SignInUser(_enteredAlias, $('#memberColumn'));
			});
			
	};
	
	$.mtgpi.loadAdminMenu = function(_targetDiv, _userAlias)
	{
		_targetDiv.append(
			$('<div>')
				.attr({'id':'adminMenuDialog', 'title':'Admin Menu'})
				.append(
					$('<a>')
						.attr({
							'href':'#'
						})
						.append($('<img>')
							.attr({
								'src':'img/close.jpg',
								'id':'closeMeeting'
							})
							.css({
								'height':'50px',
								'margin-top':'10px',
								'margin-left':'10px'
							}))
					).append($('<br>'))
					//TODO admin menu
			);
	
			$('#adminMenuDialog').dialog({
				buttons: {
					'Cancel': function()
					{
						$('#adminMenuDialog').dialog('close');
						$('#adminMenuDialog').remove();
						
						//put the cursor back in the textbox
						$('#aliasEntryBox').val('').focus();
						return;
					}
				},
				options:{
					"width": "75%",
					"height": "75%",
					"position": 'center'
				}
			});
			
			$('#closeMeeting').click(function()
			{
				$('#adminMenuDialog').remove();
				
				_targetDiv.append(
					$('<div>')
						.attr({'id':'verifyDialog', 'title':'End Meeting'})
						.append(
							"<h2>Are you sure you want to close this meeting?</h2> <br>" +
							"This will end the meeting for everyone."
						)
				);
				
				$('#verifyDialog').dialog({
					buttons: {
						'End Meeting': function()
						{
							var _mtgID = $.mtgpi.global.mtgID;
							var _user = $.mtgpi.parseAlias(_userAlias);
							var _userID = _user['UserID'];
							
							$.ajax({ 
						  	  	url:"/marc/MeetingSigninService",
						  	  	data:
						  	  	{	"RequestType":"closeMeeting", 
						  	  		"MeetingID": _mtgID,
						  	  		"UserID": _userID
						  	  	},
								type:'POST',
								dataType:"json",
								success: function(html)
								{
									$('#verifyDialog').remove();
									
									alert("Meeting closed successfully!");
									
									//TODO create viewable meeting report
									/*
									_targetDiv.append(
										$('<div>')
											.attr({'id':'meetingReport', 'title':'View Meeting Report?'})
											.append(
												"<h2>Meeting closed successfully!</h2> <br>" +
												"Would you like to view the meeting report?"
											)
									);
									
									$('#meetingReport').dialog({
										buttons: 
										{
											'Yes': function()
											{
												alert("Sorry, this feature not yet available.");
												window.location = "index.jsp";
											},
											'No': function()
											{
												$('#meetingReport').dialog('close');
												window.location = "index.jsp";
											}
										},
										width: "75%",
										height: "75%",
										options:
										{
											position: 'center'
										}
									});*/
									
									window.location = "index.jsp";
								},
						  	  	error: function(html)
								{
									alert("An error occured while closing meeting " + _mtgID +
											".\nPlease refresh your browser and try again." +
											"\n\nIf problem persists please contact BigHelp Ministries.");
								}
							}); //Closes AJAX
							
							//put the cursor back in the textbox
							$('#aliasEntryBox').val('').focus();
						},
						'Cancel': function()
						{
							$('#verifyDialog').dialog('close');
							$('#verifyDialog').remove();
							
							//put the cursor back in the textbox
							$('#aliasEntryBox').val('').focus();
						}
					},
					options:{
						"width": "75%",
						"height": "75%",
						"position": 'center'
					}
				});
			});
				
	};
	
	$.mtgpi.loadDefaultPlugin = function()
	{
		var _appBody = $('#'+$.mtgpi.global.containingDiv);
		
		_appBody.append(
			$('<center>').append(
				$('<a>')
					.attr({
						'href':'index.jsp'
					})
					.append($('<img>')
						.attr({
							'src':'img/marc_logo.jpg',
							'height':'100',
							'top':'20'
						})
					)
				)
				.append($('<br>'))
				.append($('<img>')
					.attr('src','img/logo.png')
					.css({
						'height':'250',
						'top':'15px',
						'position':'relative'
					})
				)
				.append($('<br>'))
				.append($('<form>')
					.attr('id','aliasEntryForm')
					.append($('<input>')
						.attr({
							'id':'aliasEntryBox',
							'type':'text'
						})
					)
					.css({
							'top':'65px',
							'position':'relative',
							'size':'50'
						})
					.append($('<input>')
						.attr({
							'type':'submit',
							'value':'Sign In'
						})
					)
				)
			);
		
		$('#aliasEntryForm').submit(function(e)
		{
			//Stop the form from refreshing the page
			e.preventDefault();
			
			//Get the list of active users from global, and the entered alias from the textbox
			var _enteredAlias = $('#aliasEntryBox').val();
			
			//send the data down to the SignInUser function for parsing
			$.mtgpi.SignInUser(_enteredAlias, _appBody);
		});
	};
	
	$.mtgpi.SignInUser = function(_enteredAlias, _targetDiv)
	{
		$.mtgpi.global.keepFocus = false;
		
		var _user = $.mtgpi.parseAlias(_enteredAlias);
		if(_user == -1) //if user not found
		{
			//display user not found dialog
			//create a dialog div to ask the user what they want to do with the ID
			$('#globalSettings').append(
					$('<div>')
						.attr({'id':'aliasNotFoundDialog', 'title':'Alias Not Found'})
						.append($('<center>').append($('<img>').attr('src','img/doNotEnter.png').css({'height':'200px'}))
						.append($('<br>'))
						.append($('<h2>').append("Sorry, that entry did not match any alias on record.")))
				);
				
			//create a list of users in case they decide to append the new alias to an existing user
			var _options = [];
			var _activeUsers = $.mtgpi.global.users;
			$.each(_activeUsers, function(index, _currUser) 
			{ 
				_options.push($('<option>').attr('value',_currUser['UserID']).text(_currUser['LName'] + ', ' + _currUser['Pref_Name']));
			});
			$.mtgpi.global.keepFocus = false;

			$('#aliasNotFoundDialog').dialog({
					buttons: {
						'Activate Alias (existing user)': function()
						{
							$('#aliasNotFoundDialog').dialog("close");
							
							//create the alias picker div
							_targetDiv
								.append($('<div>')
									.attr({'id':'associateAliasDialog', 'title':'New Alias Options'})
									.append($('<form>').attr({'id':'associateAliasForm'})
										.append("Who should we associate this alias with?<br>")
										.append(
											$('<select>')
												.attr('id','userToAssociateWith')
												.append(_options)
										)
									)
								);
							
							//gather the necessary information to associate the new alias	
							var _requestedUser = null;
							var _approvingAdmin = null;
							var _aliasType = "RFID"; //TODO add list of other possible alias types
										
							if($.mtgpi.global.attendantMode == false)
							{
								//turn the alias picker div into a dialog
								$('#associateAliasDialog').dialog({
									buttons: {
										'Cancel': function()
										{
											$('#associateAliasDialog').dialog("close");
										}
									}
								});
								
								//request an admin to validate the entry
								$('#associateAliasDialog')
									.append("<br><br>This action requires administrator approval.<br>")
									.append($('<form>')
										.attr({'id':'approvingAdmin'})
										.append($('<input>')
											.attr({'type':'text','id':'approvingAdminID'})
											.focus()
										)
									);
								
								//once the user's picked their name, auto-focus to the admin sign-off box
								$('#userToAssociateWith').change(function(){
									$('#approvingAdminID').focus();
								});
								
								//when the admin signs the approval, get their data
								$('#approvingAdmin').submit(function(e)
								{
									e.preventDefault();
									
									var _enteredAdmin = $('#approvingAdminID').val();
									var _parsedAdmin = $.mtgpi.parseAlias(_enteredAdmin);
									
									if(_parsedAdmin['IsAdmin'])
									{
										_requestedUser = $('#userToAssociateWith option:selected').val();
										_approvingAdmin = _parsedAdmin['UserID'];
										$.mtgpi.associateNewAlias(_requestedUser, _enteredAlias, _aliasType, _approvingAdmin);
									}
									else
									{
										alert("You are not an authorized admin!");
										
										$.mtgpi.global.keepFocus = true;
										$('#aliasEntryBox').val('').focus();
										$('#associateAliasDialog').dialog("close");
									}
								});
							}
							else
							{
								//turn the alias picker div into a dialog
								$('#associateAliasDialog').dialog({
									buttons: {
										'Activate!': function()
										{
											_approvingAdmin = $.mtgpi.global.mtgStarter;
											_requestedUser = $('#userToAssociateWith option:selected').val();
											
											$.mtgpi.associateNewAlias(_requestedUser, _enteredAlias, _aliasType, _approvingAdmin);

											$.mtgpi.global.keepFocus = true;
											$('#aliasEntryBox').val('').focus();
											$('#associateAliasDialog').dialog("close");
										},
										'Cancel': function()
										{
											$.mtgpi.global.keepFocus = true;
											$('#aliasEntryBox').val('').focus();
											$('#associateAliasDialog').dialog("close");
										}
									}
								});
							}
						}, 
						'Cancel': function()
						{
							$.mtgpi.global.keepFocus = true;
							$('#aliasEntryBox').val('').focus();
							$('#aliasNotFoundDialog').dialog("close");
						}
					}
				});
				$('#aliasNotFoundDialog').dialog( "option", "width", '75%' );
				$('#aliasNotFoundDialog').dialog( "option", "position", 'center' );
				$('#aliasEntryBox').val('').focus();
		}
		else //else if user found
		{
			if(_user['IsAlreadyIn']) //if user already in
			{
				if(_user['IsAdmin'])//admin double-tap
				{
					$.mtgpi.loadAdminMenu(_targetDiv, _user['UserID']);
				}
				else //student Double-tap
				{
					_targetDiv.append(
							$('<div>')
								.attr({'id':'2ndSwipeBox', 'title':'Double-tap Menu'})
								.append($('<center>').append($('<img>').attr('src',_user['Picture']).css({'height':'150px'})))
						);
						//turn the div into a dialog, and add some cool graphics on close
						$('#2ndSwipeBox').dialog({hide: "explode"});
						
						
						//put the cursor back in the textbox
						$('#aliasEntryBox').val('').focus();
				}

				$.mtgpi.global.keepFocus = true;
			}
			else //sign the user in
			{
				//create a welcome dialog div
				_targetDiv.append(
					$('<div>')
						.attr('id','welcomeBox')
						.append($('<h2>').append("Welcome " + _user['Pref_Name'] + "!\n"))
						.append($('<center>').append($('<img>').attr('src',_user['Picture']).css({'height':'150px'})))
				);
				
				//turn the div into a dialog, and add some cool graphics on close
				$('#welcomeBox').dialog({hide: "explode"});
				
				//AJAX - sign in user
				$.ajax({ 
			  	  	url:"/marc/MeetingSigninService",
			  	  	data:
			  	  	{
			  	  		"RequestType":"signUserIn",
			  	  		"MeetingID":$.mtgpi.global.mtgID,
			  	  		"AliasUsed":_enteredAlias,
			  	  		"UserID":_user['UserID']
			  	  	},
					type:'POST',
					dataType:"json",
					success: function(html)
					{
						//dump out the currently signed in list
						$.mtgpi.global.signedIn = [];
						
						//grab the list of currently signed in users that was passed back
						$.mtgpi.global.signedIn = html['inUsers'];
						
						//automatically close the dialog after a short time
						setTimeout(function(){$('#welcomeBox').dialog("close").remove();},1000);
						
						//put the cursor back in the textbox
						$('#aliasEntryBox').val('').focus();
					},
					error: function(html)
					{
						alert("An error occured while signing in that user." +
								"\nPlease refresh your browser and try again." +
								"\n\nIf problem persists please contact BigHelp Ministries.");
					}
				}); //Closes AJAX

				$.mtgpi.global.keepFocus = true;
			}
		}
	};
	
	$.mtgpi.associateNewAlias = function(_requestedUser, _enteredAlias, _aliasType, _approvingAdmin)
	{
		$('#associateAliasDialog').dialog("close");
		
		//AJAX to add alias to user
		$.ajax({ 
	  	  	url:"/marc/UserInfoService",
	  	  	data:
	  	  	{
	  	  		"method":"AssociateNewAlias",
	  	  		"UserID":_requestedUser,
	  	  		"Alias":_enteredAlias,
	  	  		"AliasType":_aliasType,
	  	  		"ApprovingAdmin":_approvingAdmin
	  	  	},
			type:'POST',
			dataType:"json",
			success: function(html)
			{
				if(html["Result"] == 1)
				{
					$.mtgpi.SignInUser(_requestedUser, $('#globalSettings'));
				}
				else
				{
					alert("An error occurred while associating the new alias. Please try again later.");
				}
			},
			error: function(html)
			{
				alert("An error occured while associating the new alias." +
						"\nPlease refresh your browser and try again." +
						"\n\nIf problem persists please contact BigHelp Ministries.");
			}
		}); //Closes AJAX
	};
	
	$.mtgpi.parseAlias = function(_enteredAlias)
	{
		var _aliasList = $.mtgpi.global.aliases;
		var _inList = $.mtgpi.global.signedIn;
		var _adminList = $.mtgpi.global.admins;
		var _userFound = false;
		var _isAdmin = false;
		var _alreadySignedIn = false;
		var _userDetails = [];
		
		$.each(_aliasList, function(index, _currAlias)
		{
			if(_currAlias['Alias'] == _enteredAlias)
			{
				_userFound = true;
				
				$.each(_inList, function(index, _currInUser)
				{
					if(_currInUser == _currAlias['UserID'])
					{
						_alreadySignedIn = true;
					}
				});
				$.each(_adminList, function(index, _currAdmin)
				{
					if(_currAdmin['UserID'] == _currAlias['UserID'])
					{
						_isAdmin = true;
					}
				});
				
				_userDetails['UserID'] = _currAlias['UserID'];
				_userDetails['Pref_Name'] = _currAlias['Pref_Name'];
				_userDetails['LName'] = _currAlias['LName'];
				_userDetails['Picture'] = _currAlias['Picture'];
				_userDetails['IsAlreadyIn'] = _alreadySignedIn;
				_userDetails['IsAdmin'] = _isAdmin;
			}
		});
		
		if(_userFound)
		{
			return _userDetails;
		}
		else
		{
			return -1;
		}
	};
	
	$.mtgpi.blah = function()
	{

	};
	
		
})(jQuery);